//
//  WDSliderContenerCollectionView.m
//  MyDemos
//
//  Created by iMac on 2018/3/8.
//  Copyright © 2018年 iMac. All rights reserved.
//

#import "WDSliderContenerCollectionView.h"
#import "WDSliderContenerCollectionViewCell.h"


@interface WDSliderContenerCollectionView () <UICollectionViewDelegate, UICollectionViewDataSource>


@property (nonatomic, assign) NSInteger currentIndex;
@property (nonatomic, strong) NSDictionary *viewsDict;
@property (nonatomic, strong) NSArray *collectionData;

@end

@implementation WDSliderContenerCollectionView

static NSString * const wdDSliderContenerCollectionViewCellID = @"wdDSliderContenerCollectionViewCell";

- (instancetype)initWithFrame:(CGRect)frame {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = frame.size;
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self = [super initWithFrame:frame collectionViewLayout:layout];
    if (self) {
        [self setupInit];
    }
    return self;
}

- (void)setupInit {
    self.showsVerticalScrollIndicator = NO;
    self.showsHorizontalScrollIndicator = NO;
    self.bounces = NO;
    self.pagingEnabled = YES;
    [self registerClass:[WDSliderContenerCollectionViewCell class] forCellWithReuseIdentifier:wdDSliderContenerCollectionViewCellID];
    self.delegate = self;
    self.dataSource = self;
}



- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.childViews.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    WDSliderContenerCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:wdDSliderContenerCollectionViewCellID forIndexPath:indexPath];
    cell.contenerView = self.childViews[indexPath.item];
    return cell;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSInteger index = (NSInteger)scrollView.contentOffset.x / [UIScreen mainScreen].bounds.size.width;
    self.currentIndex = index;
    if (self.didScroll) {
        self.didScroll(index);
    }
}
- (void)scrollToIndex:(NSInteger)index {
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
    if (ABS(self.currentIndex - index) == 1) {
        [self scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
    }
    else {
        [self scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }

    self.currentIndex = index;
}
- (void)toSetChildViews:(NSArray *)views {
    self.childViews = views;
    [self reloadData];
}

@end
